package cn.sinjet.phone;

import java.util.List;

import com.mgroup.wazehelper.R;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import cn.sinjet.adapter.ContactsAdapter;
import cn.sinjet.carassist.MyActivity;
import cn.sinjet.carassist.SinjetApplication;
import cn.sinjet.viewmodel.PageDefine;
import cn.sinjet.viewmodel.ViewModel;

public class ContactsActivity extends MyActivity implements OnClickListener{
	private ContactsAdapter adapterContacts;  
    private ListView vContactList;  
    List<Contact> searchResult = null;//new ArrayList<Contact>();
    
//    private QuickAlphabeticBar alphabeticBar; // 快速索引条  
    TextView vNumber;
    String strNumber = "";
    View vPhoneTab;
    Button vCallLogTab;
    Button vContactTab;
    
   @Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		super.setMyContentView(R.layout.activity_phone_contacts);
		initView();
	}
   
   private void initView(){
		   
	    vContactList = (ListView)mViewRoot.findViewById(R.id.phone_contact_list);
	    searchResult = PhoneModel.getIns(getApplicationContext()).getContacts();
		adapterContacts = new ContactsAdapter(searchResult, this);
		vContactList.setAdapter(adapterContacts);
		vContactList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
//		vContactList.setsel
		vContactList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int pos, long arg3) {
				// TODO Auto-generated method stub
//			    vContactList.setItemChecked(pos, true);
				Log.d("contact", "onItemClick:"+pos);
				adapterContacts.setSelectedPos(pos);
//				adapterContacts.
				onContactItemClk(pos);
//				vContactList.setitem
			}
		});
		/*vContactList.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) {
				// TODO Auto-generated method stub
				Log.d("contact", "onItemSelected:"+pos);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});*/
		vPhoneTab = (View)mViewRoot.findViewById(R.id.phone_tab);
		vNumber = (TextView)mViewRoot.findViewById(R.id.dial_number);
		mViewRoot.findViewById(R.id.phone_calllog_tab).setOnClickListener(this);
		mViewRoot.findViewById(R.id.btn_del).setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View arg0) {
				// TODO Auto-generated method stub
				strNumber = "";
				vNumber.setText(strNumber);
				searchInAllContacts(strNumber);
				return true;
			}
		});
   }
   
   private void onContactItemClk(int pos){
	   if(searchResult != null && pos < searchResult.size()){
		   Contact contact = searchResult.get(pos);
		   vNumber.setText(contact.getNumber().toString());
	   }
	   
	   /*if(searchResult != null || pos < searchResult.size()){
	       Contact contact = searchResult.get(pos);
//	       contact.getNumber();
	       Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ contact.getNumber()));
	       startActivity(intent);
	   }*/
   }
   @Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		ViewModel.getIns().onActivityResume(this, PageDefine.PAGE_PHONE_CONTACT, this);
		if(!PhoneModel.getIns(getApplicationContext()).isContactsLoaded()){
			//create a background thread to load the contacts
//			new Thread(new LoadPhoneRunnable(this)).start();
			new Handler().postDelayed(new LoadPhoneRunnable(this), 50);
		}
		
		if(searchResult == null){
			  searchResult = PhoneModel.getIns(getApplicationContext()).getContacts();
			  refreshList(searchResult);
		}
				
	}
   
   class LoadPhoneRunnable implements Runnable{
	   Context context;
	   public LoadPhoneRunnable(Context context){
		   this.context = context;
	   }
		@Override
		public void run() {
			// TODO Auto-generated method stub
			PhoneModel.getIns(SinjetApplication.getInstance()).loadContacts();
			PhoneModel.getIns(SinjetApplication.getInstance()).loadCalllog();
		}
   }
   
//   /**
//	 * 初始化数据库查询参数
//	 */
//	private void init() {
//		
//
//	}

	/**
	 * 
	 * @author Administrator
	 * 
	 */
	

	private void refreshList(List<Contact> list) {
		Log.d("contact", "refresh contact list");
		adapterContacts.setContactListItem(list);
		adapterContacts.notifyDataSetChanged();
//		adapter = new ContactListAdapter(this, list, alphabeticBar);
//		contactList.setAdapter(adapter);
//		alphabeticBar.init(ContactsActivity.this);
//		alphabeticBar.setListView(contactList);
//		alphabeticBar.setHight(alphabeticBar.getHeight());
//		alphabeticBar.setVisibility(View.VISIBLE)
		
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch(view.getId()){
		case R.id.btn_0:
			onClkNum("0");
			break;
		case R.id.btn_1:
			onClkNum("1");
			break;
		case R.id.btn_2:
			onClkNum("2");
			break;
		case R.id.btn_3:
			onClkNum("3");
			break;
		case R.id.btn_4:
			onClkNum("4");
			break;
		case R.id.btn_5:
			onClkNum("5");
			break;
		case R.id.btn_6:
			onClkNum("6");
			break;
		case R.id.btn_7:
			onClkNum("7");
			break;
		case R.id.btn_8:
			onClkNum("8");
			break;
		case R.id.btn_9:
			onClkNum("9");
			break;
		case R.id.btn_star:
			onClkNum("*");
			break;
		case R.id.btn_jin:
			onClkNum("#");
			break;
		case R.id.btn_del:
			if(strNumber.length()>0){
				strNumber = strNumber.substring(0, strNumber.length()-1);
				vNumber.setText(strNumber);
				searchInAllContacts(strNumber);
			}
			break;
		case R.id.phone_calllog_tab:
		    ViewModel.getIns().startActivity(CallLogActivity.class);
			break;
		case R.id.phone_dial:
			onBtnDial();
			break;
		}
	}
	
	private void onBtnDial(){
		 String str = vNumber.getText().toString().trim();
		 if(str == null || str.length() <3) return;
		 Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ str));
	     startActivity(intent);
	}
	
	private void onClkNum(String strNum){
    	if(strNumber.length()>=18)
    		return;
    	strNumber += strNum;
    	vNumber.setText(strNumber);
    	
    	searchInAllContacts(strNumber);
//    	searchResult = ContactSearch.search(strNum, allContacts);
//    	setAdapter(searchResult);
    }
	
	static int lastest = 0;
	void searchInAllContacts(final String s){
		new Thread(new Runnable() {
            final int i = ++lastest;
			@Override
			public void run() {
				if (TextUtils.isEmpty(s)) {
					// 如果输入的字符串为空，则显示所有联系人
					searchResult = PhoneModel.getIns(ContactsActivity.this).getContacts();
				} else {
					// searhContacts指向搜索返回的list
					searchResult = ContactSearch.search(s, PhoneModel.getIns(ContactsActivity.this).getContacts());
				}

				if (i == lastest) { // 避免线程同步问题
					ContactsActivity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							if (i == lastest) { // 避免线程同步问题
								/*contactList.clear();
								contactList.addAll(searchContacts);
								refreshList();*/
//								searchResult.clear();
//								searchResult
								refreshList(searchResult);
							}
						}
					});
				}
			}
		}).start();
	}
	
	@Override
	public void updateUI(Bundle data) {
		// TODO Auto-generated method stub
		super.updateUI(data);
		if(data.getInt("id",-1)==R.id.phone_contact_list){
			refreshList(PhoneModel.getIns(getApplicationContext()).getContacts());
		}
	}
}
